package com.it.emall.mapper;

import com.it.emall.domain.Ingredients;
import com.it.emall.domain.Recipes;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 *食谱Mapper
 */
@Mapper
public interface RecipeMapper {



    //食谱列表
    List<Recipes> selectRecipes(@Param("recipesId") Integer recipesId , @Param("name") String name);


    /**
     * 增加食谱点赞数
     */
    @Update("UPDATE recipes SET likes_count = likes_count + 1 WHERE id = #{recipeId}")
    int incrementLikeCount(@Param("recipeId") int recipeId);


    /**
     * 减少食谱点赞数（避免负数）
     */
    @Update("UPDATE recipes SET likes_count = GREATEST(likes_count - 1, 0) WHERE id = #{recipeId}")
    int decrementLikeCount(@Param("recipeId") int recipeId);


    /**
     * 根据食谱名称、食谱类别、食谱描述、制作步骤进行模糊查询
     * @param search 查询关键字
     * @return 食谱列表
     */
    @Select({
            "<script>",
            "SELECT * FROM recipes",
            "WHERE",
            "<if test='search != null and search != \"\"'>",
            "(recipe_name LIKE CONCAT('%', #{search}, '%')",
            "OR category LIKE CONCAT('%', #{search}, '%')",
            "OR description LIKE CONCAT('%', #{search}, '%')",
            "OR instructions LIKE CONCAT('%', #{search}, '%'))",
            "</if>",
            "</script>"
    })
    List<Recipes> searchRecipesByKeyword(String search);


    /**
     * 食谱详情页
     * @param id
     * @return
     */
    Recipes selectRecipesById(Integer id);

//    /**
//     * 用户查询自己发布的食谱
//     * @param id
//     * @param userId
//     * @return
//     */
//    Recipes selectRecipesByUserIdAndId(Integer id,Integer userId);
    /**
     * 分类详情页
     * @param ingredientId
     * @return
     */
    Recipes selectRecipesByIngredientId(Integer ingredientId);




    // 插入食谱
    int addRecipes(@Param("recipe") Recipes recipe);

    // 插入 L2 级别的食材，并返回自增 ID

    int addIngredient(Ingredients ingredient);

    /**
     * 查询发布食谱详情 用于修改食谱
     * @param userId
     * @param id
     * @return
     */
    @Select("SELECT * FROM recipes WHERE user_id = #{userId} AND id = #{id}")
    Recipes selectRecipesByuserIdUpdate(Integer userId,Integer id);


    // 更新 `recipes` 表（不修改 ingredient_id）
    @Update("UPDATE recipes SET recipe_name = #{recipe.recipeName}, description = #{recipe.description}, " +
            "instructions = #{recipe.instructions}, calories = #{recipe.calories}, protein = #{recipe.protein}, " +
            "fat = #{recipe.fat}, carbohydrate = #{recipe.carbohydrate}, image_url = #{recipe.imageUrl}, " +
            "category = #{recipe.category} " +  // 只更新 category，不更新 ingredient_id
            "WHERE id = #{recipe.id} AND user_id = #{recipe.userId}")
    int updateRecipe(@Param("recipe") Recipes recipe);

    // 更新 `ingredients` 表
    @Update("UPDATE ingredients " +
            "SET name = (SELECT category FROM recipes WHERE id = #{id}), " +
            "pid = #{pid}, " +
            "pic_url = (SELECT image_url FROM recipes WHERE id = #{id}), " +
            "icon_url = (SELECT image_url FROM recipes WHERE id = #{id}), " +
            "level = 'L2' " +
            "WHERE id = (SELECT ingredient_id FROM recipes WHERE id = #{id})")
    int updateIngredientsCategory(@Param("id") Integer id, @Param("pid") Integer pid);

    // 删除食谱（仅限该用户的食谱）
    // 先删除 ingredients 表中的对应数据
    @Delete("DELETE FROM ingredients WHERE id = (SELECT ingredient_id FROM recipes WHERE id = #{id} AND user_id = #{userId})")
    int deleteIngredientByRecipeId(Integer id, Integer userId);

    // 再删除 recipes 表中的数据
    @Delete("DELETE FROM recipes WHERE id = #{id} AND user_id = #{userId}")
    int deleteRecipeById(Integer id, Integer userId);

    // 根据用户ID查询该用户发布的所有食谱
    @Select("SELECT * FROM recipes WHERE user_id = #{userId}")
    List<Recipes> getRecipesByUserId(Integer userId);


    /**
     *后台
     */

    //食谱列表
    List<Recipes> selectManageRecipes();

    List<Recipes> searchManageRecipes(@Param("recipeName") String recipeName,
                               @Param("category") String category,
                               @Param("description") String description,
                               @Param("instructions") String instructions);

    int insertManageRecipe(Recipes recipe);

    int updateManageRecipe(Recipes recipe);

    int deleteManageRecipe(@Param("id") Integer id);
}
